/*---- talent.ui.Grid start ----*/
talent.Ns.add("talent.ui.GridProxy"); // 此非全局命名空间，所以在此定义
talent.ui.GridProxy = {
    index : -1
};

/**
 * 显示ajax返回的信息
 *
 * @param {}
 *            retObj
 */
function tt_showResult(retObj, isAlertWhenSuccess, isAlertWhenFail) {
    if (retObj) {
        if (retObj.result == 1) { // 业务上成功
            if (isAlertWhenSuccess) {
                $.messager.alert(retObj.title, retObj.msg);
            }
            return true;
        } else {
            if (isAlertWhenFail == undefined) {
                $.messager.alert(retObj.title, retObj.msg, 'error');
            }
            return false;
        }
    }
    return false;
}

function tt_beforeSend(msgContainEle) {
    if (msgContainEle) {
        msgContainEle.innerHTML = "<div class='tt_grid_load'></div>";
    } else {
        $.messager.progress({
            title : '正在处理... ...',
            msg : '正在处理，请稍后... ...'
        });
    }
}

function tt_complete(msgContainEle) {
    try {
        if (msgContainEle) {
            msgContainEle.innerHTML = "";
        } else {
            $.messager.progress('close');
        }
    } catch (e) {
    }
}

/**
 * grid刷新
 *
 * @param {}
 *            gridConfig
 * @param {}
 *            pageIndex
 * @param {}
 *            pageSize
 */
var tt_refresh = function(gridConfig, pageIndex, pageSize) {
    this.h = function() {
        talent.ui.GridProxy[gridConfig.name].reload(pageIndex, pageSize);
    };
};

function tt_checkboxHeadRender(conf) {
    var checkboxAll = tt_ce("input");
    checkboxAll.type = "checkbox";
    conf.cell.appendChild(checkboxAll);
    checkboxAll.style.cursor = "pointer";
    checkboxAll.title = "全选/全取消";
    $(checkboxAll).attr("id", "tt_gridCheckbox_all");
    // talent.Util.addEventHandler(checkboxAll, "change", tt_gridSelectAll);
    // talent.Util.addEventHandler(checkboxAll, "click", tt_gridSelectAll);

    tt_autoUpdateCheckbox("tt_gridCheckbox", checkboxAll);
}

function tt_checkboxListRender(conf) {
    var cloneConfig = {};
    talent.Util.copy(cloneConfig, conf);

    var checkbox = talent.Util.createInputElement('checkbox');
    cloneConfig.cell.appendChild(checkbox);
    var $checkbox = $(checkbox);

    checkbox.config = cloneConfig;
    $checkbox.attr("name", "tt_gridCheckbox");
    tt_autoUpdateCheckbox1(checkbox, "tt_gridCheckbox", document
        .getElementById("tt_gridCheckbox_all"));
}

var tt_checkboxField = {
    name : "tt_checkbox",
    label : "",
    headerCellRenderConfig : {
        clazz : tt_checkboxHeadRender
    },
    dataCellRenderConfig : {
        clazz : tt_checkboxListRender
    },
    headerCellProps : {
        width : "50px"
    }
};

function tt_gridDecorateRow(conf, row, rowClassName) {
    if (conf.highlight) {
        var _className = conf.highlight.className;
        if (!_className) {
            _className = "talent_grid_highlight";
        }
        var h = function(target, type) {
            this.p = function() {
                if (type == "1") {
                    tt_grid_addCls(target, _className, conf.colorStyle);
                } else if (type == "0") {
                    tt_grid_rmCls(target, _className, conf.colorStyle);
                }
            };
        };

        talent.Util.addEventHandler(row, "mouseover", new h(row, "1").p);
        talent.Util.addEventHandler(row, "mouseout", new h(row, "0").p);
    }
    tt_grid_addCls(row, rowClassName, conf.colorStyle);
}

/**
 * key配置
 *
 * @type
 */
talent.ui.gridKeyConfig = { // talent.ui.gridKeyConfig
    pageCount : "pageCount",
    pageIndex : "pageIndex",
    pageSize : "pageSize",
    pagination : "pagination",
    recordCount : "recordCount",
    data : "data"
};

function tt_grid_addCls(obj, clsName, colorStyle) {
    talent.Util.addClass(obj, clsName + colorStyle);
}
function tt_grid_rmCls(obj, clsName, colorStyle) {
    talent.Util.removeClass(obj, clsName + colorStyle);
}

/**
 * @param {}
 *            conf grid配置，参见demo_page.js中的conf conf.gridContext： grid数据，形如：<br>
 *
 * <pre>
 *  {
 *  &quot;keyConfig&quot;:{
 *  pageCount: &quot;pageCount&quot;,
 *  pageIndex: &quot;pageIndex&quot;,
 *  pageSize: &quot;pageSize&quot;,
 *  pagination: &quot;pagination&quot;,
 *  recordCount: &quot;recordCount&quot;,
 *  data: &quot;data&quot;
 *  },
 *  &quot;data&quot;:
 *  [
 *  {
 *  &quot;name&quot;: &quot;乔丹&quot;,
 *  &quot;id&quot;: &quot;1&quot;
 *  },
 *  {
 *  &quot;name&quot;: &quot;科比&quot;,
 *  &quot;id&quot;: &quot;2&quot;
 *  }
 *  ],
 *  &quot;colorStyle&quot;: &quot;green&quot;,
 *  &quot;name&quot;: &quot;grid_1&quot;,    //用来保存当前grid对象的key值
 *  &quot;showHeader&quot;:true,   //是否显示头
 *  &quot;pageCount&quot;: 100,  //总页数
 *  &quot;pageIndex&quot;: 6,    //当前是第几页
 *  &quot;pageSize&quot;: 2,     //每页显示多少条
 *  &quot;pagination&quot;: true,//如果不想分页，请将此属性设为false
 *  &quot;recordCount&quot;: 500//总记录数
 *  }
 * </pre>
 *
 * conf.container 显示grid数据的容器，一般为一个div对象 可以通过grid对象获取下面这些元素
 *            this.thead = thead; this.tbody = tbody; this.tfoot = tfoot;
 *            this.table = table; this.ext = {'addedRows':[7,8,9],
 *            'deletedRows':[0,1,5],'edittedRows':[0,1,2]};
 */
talent.ui.Grid = function(conf) {
    conf.ext = {};
    conf.name = conf.name ? conf.name : ++talent.ui.GridProxy.index;
    conf.keyConfig = conf.keyConfig ? conf.keyConfig : talent.ui.gridKeyConfig;
    conf.showHeader = conf.showHeader == undefined ? true : conf.showHeader;
    conf.showFirstHeader = conf.showFirstHeader == undefined
        ? true
        : conf.showFirstHeader;
    conf.colorStyle = !conf.colorStyle ? "" : "_" + conf.colorStyle;
    conf.highlight = conf.highlight == undefined ? {} : conf.highlight;

    conf.isShowCustomPageSize = conf.isShowCustomPageSize == undefined ? true : conf.isShowCustomPageSize;
    conf.renderGo = conf.renderGo == undefined ? true : conf.renderGo;
    conf.totalRecordI18 = conf.totalRecordI18 == undefined ? "共{}条" : conf.totalRecordI18;

    conf.paginationCount = conf.paginationCount == undefined ? 5 : conf.paginationCount;

    conf.canClose = conf.canClose == undefined ? false : conf.canClose;
    conf.canSlide = conf.canSlide == undefined ? true : conf.canSlide;
    conf.canRefresh = conf.canRefresh == undefined ? true : conf.canRefresh;
    conf.firstHeaderTitle = conf.firstHeaderTitle == undefined
        ? ""
        : conf.firstHeaderTitle;

    conf.noRecordText = conf.noRecordText == undefined
        ? "没查询到数据"
        : conf.noRecordText;

    tt_grid_addCls(conf.container, "tt_grid_container", conf.colorStyle);

    this.config = conf;
    this.initExtData = function() {
        if (conf.isShowCheckbox) {
            conf.fields = [tt_checkboxField].concat(conf.fields);
        }

        conf.colsCount = conf.fields.length; // 有多少列要显示
        // conf.dataRows = conf.gridContext.data.length;
        for (var i = 0; i < conf.fields.length; i++) {
            var f = conf.fields[i];
            f.display = (f.display == undefined) ? true : f.display;
            if (!f.display) {
                conf.colsCount--;
            }
            /**
             * if (f.colSpan && f.colSpan > 1) { conf.colsCount += (f.colSpan -
			 * 1); } if (f.rowSpan && f.rowSpan > 1) { //conf.dataRows +=
			 * (f.rowSpan - 1) * conf.gridContext.data.length; }
             */
        }
    };
    this.initExtData();

    // 设置当前对象的代理对象，以方便第三方函数引用本对象
    talent.ui.GridProxy[conf.name] = this;

    /**
     *
     */
    this.render = function() {
        var conf = this.config;
        var gridContext = conf.gridContext;

        if (conf.dataFilter) {
            gridContext = conf.dataFilter.call(this, gridContext);
            conf.gridContext = gridContext;
        }

        if (!conf.errorTitle) {
            gridContext.pageIndex = gridContext[conf.keyConfig.pageIndex];
            gridContext.pageSize = gridContext[conf.keyConfig.pageSize];
            gridContext.pagination = gridContext[conf.keyConfig.pagination];
            gridContext.recordCount = gridContext[conf.keyConfig.recordCount];
            gridContext.data = gridContext[conf.keyConfig.data];

            if (gridContext.pageSize >= gridContext.recordCount
                && gridContext.recordCount < 1) {
                gridContext.pagination = false;
            }

            if (!gridContext.recordCount) {
                gridContext.recordCount = gridContext.data.length;
                gridContext.pageSize = gridContext.pageSize || 10;
                gridContext.pageIndex = gridContext.pageIndex || 1;
            }

            gridContext.pagination = (gridContext.pagination == undefined || gridContext.pagination);

            gridContext.prePageCount = gridContext.pageIndex - 1;
            gridContext.prePageCount = gridContext.prePageCount < 0
                ? 0
                : gridContext.prePageCount;

            gridContext.pageCount = parseInt((gridContext.recordCount
                + gridContext.pageSize - 1)
                / gridContext.pageSize);

            gridContext.sufPageCount = gridContext.pageCount
                - gridContext.pageIndex;
            gridContext.sufPageCount = gridContext.sufPageCount < 0
                ? 0
                : gridContext.sufPageCount;
        }

        if (conf.renderConfig && conf.renderConfig.clazz) {
            var cfg = {};
            talent.Util.copy(cfg, conf.renderConfig.config);
            cfg.gridConfig = conf;
            cfg.gridContext = conf.gridContext;

            conf.renderConfig.clazz.call(conf.renderConfig.clazz, cfg);
            return;
        }

        conf.container.innerHTML = "";
        conf.container.style.display = "";
        // $(conf.container).slideDown("fast");

        var div4table = tt_ce("div");
        conf.container.appendChild(div4table);
        div4table.style.overflow = "auto";

        // table
        var table = tt_ce("table");
        this.table = table;
        tt_grid_addCls(table, "talent_grid_table", conf.colorStyle);
        div4table.appendChild(table);

        // 收起、打开、关闭 start
        if (conf.showFirstHeader) {
            // conf.firstHeaderTitle
            var divBar = tt_ce("div");
            conf.container.appendChild(divBar);
            $(divBar).insertBefore(div4table);

//			//筛选
//			if (conf.canRefresh) {
//				var refreshSpan = tt_ce("span");
//				divBar.appendChild(refreshSpan);
//
//				var refreshA = tt_ce("a");
//				divBar.appendChild(refreshA);
//				refreshA.title = "设置筛选条件";
//				tt_grid_addCls(refreshA, "search", conf.colorStyle);
//				refreshA.href = 'javascript:void(0)';
//
//				var gridself = talent.ui.GridProxy[conf.name];
//				var refresh = new tt_refresh(conf, 0, 10);
//				talent.Util.addEventHandler(refreshA, "click", refresh.h);
//			}

            // 刷新图标
            if (conf.canRefresh) {
                var refreshSpan = tt_ce("span");
                divBar.appendChild(refreshSpan);

                var refreshA = tt_ce("a");
                divBar.appendChild(refreshA);
                refreshA.title = "刷新";
                tt_grid_addCls(refreshA, "refresh", conf.colorStyle);
                refreshA.href = 'javascript:void(0)';

                var refresh = new tt_refresh(conf, 0, 10);
                talent.Util.addEventHandler(refreshA, "click", refresh.h);
            }

            // first header title
            if (conf.firstHeaderTitle) {
                var div = tt_ce("div");
                divBar.appendChild(div);
                if (jQuery.isFunction(conf.firstHeaderTitle)){
                    conf.firstHeaderTitle.call(conf.firstHeaderTitle, div, conf);
                } else {
                    div.innerHTML = conf.firstHeaderTitle;
                }

            }

            tt_grid_addCls(divBar, "tt_grid_first_header", conf.colorStyle);

            // 关闭按钮
            if (conf.canClose) {
                var closeA = null;
                closeA = tt_ce("a");
                divBar.appendChild(closeA);
                tt_grid_addCls(closeA, "tt_float_right close", conf.colorStyle);
                closeA.href = 'javascript:void(0)';

                var callback = null;
                if (conf.closeCallback){
                    callback = conf.closeCallback;
                }

                var h2 = new tt_slideUp(conf.container, null, null, callback);
                talent.Util.addEventHandler(closeA, "click", h2.slideUp);
            }

            if (conf.canSlide){
                // 收起图标
                var slideUpA = tt_ce("a");
                divBar.appendChild(slideUpA);
                tt_grid_addCls(slideUpA, "tt_float_right slideUp", conf.colorStyle);
                slideUpA.title="收起";
                slideUpA.href = 'javascript:void(0)';

                // 下拉图标
                var slideDownA = tt_ce("a");
                divBar.appendChild(slideDownA);
                tt_grid_addCls(slideDownA, "tt_float_right slideDown",
                    conf.colorStyle);
                slideDownA.title = "显示";
                slideDownA.href = 'javascript:void(0)';
                slideDownA.style.display = "none";

                // 添加事件
                var h1 = new tt_slideUp(table, slideUpA, slideDownA);
                talent.Util.addEventHandler(slideDownA, "click", h1.slideDown);
                talent.Util.addEventHandler(slideUpA, "click", h1.slideUp);
            }
        }
        // 收起、打开、关闭 end

        var caption = null;
        var thead = tt_ce("thead");
        var tbody = tt_ce("tbody");
        var tfoot = tt_ce("tfoot");
        this.thead = thead;
        this.tbody = tbody;
        this.tfoot = tfoot;

        if (conf.errorTitle) { // 出错
            table.appendChild(tbody);

            var rowIndex = tbody.rows.length;
            var row = tbody.insertRow(rowIndex);
            var cell = row.insertCell(row.cells.length);
            cell.setAttribute("colspan", conf.fields.length);
            cell.innerHTML += "<div class='tt_grid_loadfail" + conf.colorStyle
                + "'>" + conf.errorMsg + "</div>";
            return;
        } else if (!conf.gridContext.data || conf.gridContext.data.length == 0) { // 没有数据
            table.appendChild(tbody);

            var rowIndex = tbody.rows.length;
            var row = tbody.insertRow(rowIndex);
            var cell = row.insertCell(row.cells.length);
            cell.setAttribute("colspan", conf.fields.length);
            cell.innerHTML += "<div class='tt_no_record" + conf.colorStyle
                + "'>" + conf.noRecordText + "</div>";
            cell.style.borderTop = "none";
            return;
        } else {
            if (conf.caption) {
                caption = tt_ce("caption");
                table.appendChild(caption);
            }
            table.appendChild(thead);
            table.appendChild(tbody);
            table.appendChild(tfoot);
        }

        conf.captionRender ? conf.captionRender.call(conf.captionRender, table,
            caption, conf) : this.renderCaption(table, caption, conf);
        conf.theadRender ? conf.theadRender.call(conf.theadRender, table,
            thead, conf) : this.renderThead(table, thead, conf);
        conf.tbodyRender ? conf.tbodyRender.call(conf.tbodyRender, table,
            tbody, conf) : this.renderTbody(table, tbody, conf);
        conf.tfootRender ? conf.tfootRender.call(conf.tfootRender, table,
            tfoot, conf) : this.renderTfoot(table, tfoot, conf);
    };

    this.renderCaption = function(table, caption, conf) {
        if (conf.caption) {
            if (conf.caption.render) {
                conf.caption.render.call(window, table, caption,
                    conf.gridContext, conf);
            } else if (conf.caption.label) {
                caption.innerHTML = conf.caption.label;
            }
        }
    };
    /**
     *
     */
    this.renderThead = function(table, thead, conf) {
        if (!conf.showHeader) {
            return;
        }
        var gridContext = conf.gridContext;
        if (gridContext.pagination) {

            var divForPagination = null;

            if (conf.headerTopRenderConfig) {
                divForPagination = tt_ce("div");

                var row = thead.insertRow(0);
                var cell = row.insertCell(0);
                cell.setAttribute('colspan', conf.fields.length);
                // cell.appendChild(divForPagination);
                // $(divForPagination).insertBefore(table);

                tt_grid_addCls(divForPagination, "digg", conf.colorStyle);
                cell.style.borderTop = "none";
                // divForPagination.style.border = "none";
                row.style.border = "none";
                cell.style.textAlign = "left";
                cell.style.fontWeight = "normal";
                tt_grid_addCls(cell, "tt_grid_second_header", conf.colorStyle);

                if (conf.headerTopRenderConfig.clazz) {
                    var cfg = {};
                    talent.Util.copy(cfg, conf.headerTopRenderConfig.config);
                    cfg.cell = cell;
                    conf.headerTopRenderConfig.clazz.call(
                        conf.headerTopRenderConfig.clazz, cfg);
                }
            }
        }

        var theadRow = thead.insertRow(thead.rows.length);
        for (var fieldIndex = 0; fieldIndex < conf.fields.length; fieldIndex++) {
            var f = conf.fields[fieldIndex];
            if (!f.display) {
                continue;
            }
            var cell = tt_ce("th");
            theadRow.appendChild(cell);
            talent.Util.copy(cell, f.headerCellProps);
            talent.Util.setStyle(cell, f.headerCellStyle);
            // table, rowElement, cell, fieldConfig, conf, gridContext
            // table, rowElement, cell, fieldConfig, conf, gridContext
            if (f.headerCellRenderConfig && f.headerCellRenderConfig.clazz) {
                var cfg = {};
                talent.Util.copy(cfg, f.headerCellRenderConfig.config);
                cfg.field = f;
                cfg.gridConfig = conf;
                cfg.gridContext = gridContext;
                cfg.rowElement = theadRow;
                cfg.cell = cell;

                f.headerCellRenderConfig.clazz.call(
                    f.headerCellRenderConfig.clazz, cfg);

            } else if (f.label) {
                cell.innerHTML = f.label;
            }
        }
    };
    this.renderTbody = function(table, tbody, conf) {

        var prefix = "talent_grid_table_tbody_row_";
        var rowClassName = prefix + "even";
        var gridContext = conf.gridContext;

        // var dataIndex = 0;
        for (var i = 0; i < conf.gridContext.data.length; i++) {
            var rowIndex = tbody.rows.length;
            var row = tbody.insertRow(rowIndex);

            tt_gridDecorateRow(conf, row, rowClassName, rowIndex);
            rowClassName = rowClassName == prefix + "even"
                ? prefix + "odd"
                : prefix + "even";

            if (!conf.ext.deletedRows) {
                conf.ext.deletedRows = [];
            }
            if (!conf.ext.edittedRows) {
                conf.ext.edittedRows = [];
            }
            if (conf.ext.deletedRows.ttCons(rowIndex)) {
                tt_grid_addCls(row, "tt_grid_deleted_row", conf.colorStyle);
                row.title = conf.ext.deletedTitle || "该记录已被删除";
                row.setAttribute("disabled", true);
                row.disabled = true;
                row.tt_deleted = true;
            }
            if (conf.ext.edittedRows.ttCons(rowIndex)) {
                tt_grid_addCls(row, "tt_grid_editted_row", conf.colorStyle);
                row.title = conf.ext.edittedTitle || "该记录刚才被修改过";
            }

            for (var fieldIndex = 0; fieldIndex < conf.fields.length; fieldIndex++) {
                var f = conf.fields[fieldIndex];
                if (!f.display) {
                    continue;
                }
                var cell = row.insertCell(row.cells.length);
                talent.Util.copy(cell, f.dataCellProps);
                talent.Util.setStyle(cell, f.dataCellStyle);
                // (rowElement, cell, rowData, fieldConfig, conf,
                // gridContext)

                // table, row, cell, gridContext.data[i], f, conf, gridContext,
                // i, fieldIndex
                // table, rowElement, cell, rowData, fieldConfig,
                // gridConfig, gridContext, rowIndex, colIndex
                if (gridContext.data[i]) {
                    if (row.tt_deleted) {
                        if (f.dataCellRenderConfig
                            && f.dataCellRenderConfig.clazz) {

                        } else {
                            var l = gridContext.data[i][conf.fields[fieldIndex].name];
                            if (l != null && l != undefined) {
                                cell.innerHTML = l;
                            }
                        }
                    } else if (f.dataCellRenderConfig
                        && f.dataCellRenderConfig.clazz) {
                        var _ = {};
                        talent.Util.copy(_, f.dataCellRenderConfig.config);
                        _.table = table;
                        _.field = f;
                        _.gridConfig = conf;
                        _.gridContext = gridContext;
                        _.rowIndex = i;
                        _.colIndex = fieldIndex;
                        _.rowElement = row;
                        _.cell = cell;
                        _.rowData = gridContext.data[i];
                        _.value = _.rowData[f.name];
                        _.value = !_.value ? "" : _.value;

                        f.dataCellRenderConfig.clazz.call(
                            f.dataCellRenderConfig.clazz, _);
                    } else {
                        var l = gridContext.data[i][conf.fields[fieldIndex].name];
                        if (l != null && l != undefined) {
                            cell.innerHTML = l;
                        }
                    }
                }
            }
        }

        if (conf.dataDecoratorConfig && conf.dataDecoratorConfig.after) {
            var rowIndex = tbody.rows.length;
            var row = tbody.insertRow(rowIndex);

            tt_gridDecorateRow(conf, row, rowClassName, rowIndex);
            rowClassName = rowClassName == prefix + "even"
                ? prefix + "odd"
                : prefix + "even";

            var _ = {};
            _.table = table;
            _.gridConfig = conf;
            _.gridContext = gridContext;
            _.rowIndex = rowIndex;
            _.rowElement = row;
            // table, tbody, conf
            conf.dataDecoratorConfig.after.call(conf.dataDecoratorConfig.after,
                _);
        }
    };
    this.renderTfoot = function(table, tfoot, conf) {
        var gridContext = conf.gridContext;
        if (gridContext.pagination) {

            var row = tfoot.insertRow(tfoot.rows.length);
            var cell = row.insertCell(row.cells.length);
            cell.colSpan = conf.colsCount;
            var footdiv = tt_ce("div");
            cell.appendChild(footdiv);
            tt_grid_addCls(footdiv, "digg", conf.colorStyle);
            this.renderPagination(footdiv, conf);
        }
    };

    this.renderPagination = function(div, conf) {
        // div.innerHTML = "";

        if (conf.paginationRender) {
            conf.paginationRender.call(conf.paginationRender, div, conf);
            return;
        }
        // this.renderPaginationSeperator(div, conf);
        this.renderPaginationMsg(div, conf);


        if (conf.renderGo) {
            this.renderPaginationGoto(div, conf);
            this.renderPaginationSeperator(div, conf);
        }

        if(conf.gridContext.pageCount > 1) {
            this.renderPaginationSeperator(div, conf);
            this.renderPaginationPre(div, conf);
            this.renderPaginationCurr(div, conf);
            this.renderPaginationSuffix(div, conf);
        }

        if (conf.isShowCustomPageSize == null
            || conf.isShowCustomPageSize == undefined
            || conf.isShowCustomPageSize == true) {
            this.renderPaginationSeperator(div, conf);
            new paginationCustomPageSizeRender(div, conf).render();
            // this.renderPaginationSeperator(div, conf);
        }
    };

    /**
     * 渲染分隔符：|
     */
    this.renderPaginationSeperator = function(div, conf) {
        var span = tt_ce("span");
        div.appendChild(span);
        // span.innerHTML = "|";
        tt_grid_addCls(span, "separator", conf.colorStyle);
    };

    /**
     * 渲染：1-10 / 60
     */
    this.renderPaginationMsg = function(div, conf) {
        var gridContext = conf.gridContext;

        var e = gridContext.pageIndex * gridContext.pageSize;
        e = e > gridContext.recordCount ? gridContext.recordCount : e;
        // alert(gridContext.currPageSize);
        if (gridContext.currPageSize) {
            e = gridContext.currPageSize;
        }

        var s = ((gridContext.pageIndex - 1) * gridContext.pageSize + 1);
        s = s < 0 ? 0 : s;

//		var span1 = tt_ce("span");
//		div.appendChild(span1);
//		span1.innerHTML = gridContext.pageIndex + "/" + gridContext.pageCount
//				+ "页";
//		this.renderPaginationSeperator(div, conf);

        var span2 = tt_ce("span");
        div.appendChild(span2);
        span2.innerHTML = conf.totalRecordI18.replace("{}", gridContext.recordCount);
    };

    /**
     * 渲染"第一页和上一页"，如果没有则不渲染.
     */
    this.renderPaginationPre = function(div, conf) {
        var gridContext = conf.gridContext;
        if (gridContext.prePageCount <= 0) {

        } else {
            // <a href="#?page=2"> &gt;&gt; </a>
            /* 第一页和上一页 start */
            var a1 = tt_ce("a");
            div.appendChild(a1);
            processAObj(a1, 1, conf);
            a1.innerHTML = "";
            tt_grid_addCls(a1, "arrow", conf.colorStyle);
            tt_grid_addCls(a1, "first", conf.colorStyle);

            var a2 = tt_ce("a");
            div.appendChild(a2);
            processAObj(a2, gridContext.pageIndex - 1, conf);
            a2.innerHTML = "";
            tt_grid_addCls(a2, "arrow", conf.colorStyle);
            tt_grid_addCls(a2, "pre", conf.colorStyle);

            /* 第一页和上一页 end */
            /* <a href="#?page=2">2</a> */
            if (conf.paginationCount > 0) {
                var preIndexCount = gridContext.prePageCount > conf.paginationCount
                    ? conf.paginationCount
                    : gridContext.prePageCount;
                for (var i = preIndexCount; i > 0; i--) {
                    // gridContext.pageIndex - i;
                    var a = tt_ce("a");
                    div.appendChild(a);
                    var _index = gridContext.pageIndex - i;
                    processAObj(a, _index, conf);
                    a.innerHTML = _index;
                }
            }

        }
    };
    this.renderPaginationCurr = function(div, conf) {
        // <span class="current">1</span>
        if (conf.paginationCount > 0) {
            var a1 = tt_ce("span");
            div.appendChild(a1);
            tt_grid_addCls(a1, "current", conf.colorStyle);
            a1.innerHTML = conf.gridContext.pageIndex;
            a1.href="javascript:void(0);";
        }
    };
    this.renderPaginationSuffix = function(div, conf) {
        var gridContext = conf.gridContext;
        if (gridContext.sufPageCount <= 0) {

        } else {
            /* <a href="#?page=2">2</a> */
            var sufIndexCount = 0;
            if (conf.paginationCount > 0) {
                sufIndexCount = gridContext.sufPageCount > conf.paginationCount
                    ? conf.paginationCount
                    : gridContext.sufPageCount;
                for (var i = 1; i <= sufIndexCount; i++) {
                    // gridContext.pageIndex - i;
                    var a = tt_ce("a");
                    div.appendChild(a);
                    var _index = gridContext.pageIndex + i;
                    processAObj(a, _index, conf);
                    a.innerHTML = _index;
                }
            }

            // 最后一页需要渲染，这样可以看出有多少页
            if (gridContext.pageCount > sufIndexCount + gridContext.pageIndex) {

                if (gridContext.pageCount > sufIndexCount
                    + gridContext.pageIndex + 1) {
                    var span1 = tt_ce("span");
                    div.appendChild(span1);
                    span1.innerHTML = "...";
                }

                var a = tt_ce("a");
                div.appendChild(a);
                processAObj(a, gridContext.pageCount, conf);
                a.innerHTML = gridContext.pageCount;
            }

            // <a href="#?page=2"> &gt;&gt; </a>
            /* 最后页和下一页 start */
            var a1 = tt_ce("a");
            div.appendChild(a1);
            processAObj(a1, gridContext.pageIndex + 1, conf);
            a1.innerHTML = "";
            tt_grid_addCls(a1, "arrow", conf.colorStyle);
            tt_grid_addCls(a1, "next", conf.colorStyle);

            var a2 = tt_ce("a");
            div.appendChild(a2);
            processAObj(a2, gridContext.pageCount, conf);
            a2.innerHTML = "";
            tt_grid_addCls(a2, "arrow", conf.colorStyle);
            tt_grid_addCls(a2, "last", conf.colorStyle);
            /* 最后页和下一页 end */
        }
    };
    this.renderPaginationGoto = function(div, conf) {
        var span1 = tt_ce("span");
        div.appendChild(span1);
        tt_grid_addCls(span1, "goto", conf.colorStyle);
        span1.innerHTML = "跳转";

        var spanInput = tt_ce("span");
        div.appendChild(spanInput);

        var span2 = tt_ce("span");
        div.appendChild(span2);
        tt_grid_addCls(span2, "goto", conf.colorStyle);

        var p = tt_ce("input");
        spanInput.appendChild(p);
        tt_grid_addCls(p, "goto_input", conf.colorStyle);
        p.type = 'text';
        p.value = conf.gridContext.pageIndex;
        p.title = "输入页码，然后按回车键";
        // try{$(p).tooltip({'title':p.title});}catch(e){} //加tooltip

        try {
            tt.vf.num.addObj(p);
        } catch (e) {
        } // 加数字验证

        $(p).keydown(function(event) {
            var keycode = event.which;
            if (keycode == 13) {
                try {
                    $(p).tooltip('hide');
                } catch (e) {
                }
                if (tt.validateElement(p)) {
                    talent.ui.GridProxy[conf.name].reload(p.value);
                }
            }
        });
    };

    // processAObj(a,pageIndex);
    var processAObj = function(aObj, pageIndex, gridConfig) {
        aObj.href = "javascript:void(0)";
        // alert(pageIndex);
        var h = function(pageIndex) {
            this.a = function() {
                talent.ui.GridProxy[gridConfig.name].reload(pageIndex);
            };
        };
        talent.Util.addEventHandler(aObj, "click", new h(pageIndex).a);
    };
    /**
     *
     */
    this.reload = function(pageIndex, _pageSize) {
        this.config.ext = {};
        conf = this.config;
        var pageSize = 10;

        if (_pageSize) {
            pageSize = _pageSize;
        } else if (conf.gridContext && conf.gridContext.pageSize) {
            pageSize = conf.gridContext.pageSize;
        }

        var postData = [];
        postData.push(conf.keyConfig.pageIndex + "=" + pageIndex + "&"
            + conf.keyConfig.pageSize + "=" + pageSize);
        // [{name:conf.keyConfig.pageIndex, value:
        // pageIndex},{name:conf.keyConfig.pageSize, value:pageSize}];
        if (conf.form) {
            postData.push($(conf.form).serialize());
        }
        if (conf.queryStringData) {
            postData.push(encodeURI(conf.queryStringData));
        }
        if (conf.postData) {
            var data;
            for (var i = 0; i < conf.postData.length; i++) {
                data = conf.postData[i];
                postData.push(data.name + "=" + encodeURIComponent(data.value));
            }
        }
        
        if (conf.postDataHandler){
        	conf.postDataHandler.call(conf, postData);
        }
        
        var postDataStr = postData.join("&");
        postDataStr = tt_skipEmptyValue(postDataStr);

        var _grid = this;

        var ajaxConf = {
            url : conf.url,
            data : postDataStr,
            type : "POST",
            dataType : "jsonp",
    		jsonp : "tio_http_jsonp",
    		scriptCharset : 'UTF-8',
            "_grid" : _grid,
           

            success : function(retObj) {
                this._grid.renderData(retObj);
            }
        };

        talent.Util.copy(ajaxConf, conf.ajaxConf);
        $.ajax(ajaxConf);
    };

    this.renderData = function (retObj){
        var conf = this.config;
        tt_complete(conf.container);
        var result = tt_showResult(retObj, false, true);
        if (result) {
            conf.errorTitle = null;
            conf.errorMsg = null;
            this.config.gridContext = retObj.data;
            this.render();
        } else {
            conf.errorTitle = retObj.title + "";
            conf.errorMsg = retObj.msg + "";
            this.config.gridContext = retObj.data;
            this.render();
        }
        
        if (conf.callback){
        	conf.callback.call(conf.callback, conf);
        }
    };
};

var paginationCustomPageSizeRender = function(div, conf) {
    var gridContext = conf.gridContext;
    this.render = function() {
        ops = [];
        maxPageSize = 200;
        if (conf.maxPageSize && !isNaN(conf.maxPageSize)) {
            maxPageSize = conf.maxPageSize;
        }
        maxPageSize = maxPageSize > gridContext.recordCount
            ? gridContext.recordCount
            : maxPageSize;

        if (maxPageSize >= 5) {
            ops.push({
                v : 5,
                l : 5
            });
        }
        if (maxPageSize >= 10) {
            ops.push({
                v : 10,
                l : 10
            });
        }

        var step = 20;
        for (var i = 20; i <= maxPageSize; i += step) {
            ops.push({
                v : i,
                l : i
            });
            if (i >= 1000) {
                step = 100;
            } else if (i >= 500) {
                step = 50;
            }
        }
        if (gridContext.recordCount <= maxPageSize
            && gridContext.recordCount > 0) {// RecordCount
            ops.push({
                v : gridContext.recordCount,
                l : "全部"
            });
        }

        // alert(ops[0].l);
        if (ops.length > 0) {
            var span = tt_ce("span");
            div.appendChild(span);
            span.innerHTML = "每页显示";

            var selectElement = tt_ce("select");
            div.appendChild(selectElement);
            var _h = function(pageindex, pagesizeO) {
                var f = function() {
                    talent.ui.GridProxy[conf.name].reload(pageindex,
                        pagesizeO.value);
                };
                return f;
            };
            talent.Util.addEventHandler(selectElement, "change", new _h(
                gridContext.pageIndex, selectElement));
            talent.Util.updateOption(selectElement, "true", ops, "v", "l",
                true, null, null, null);

            if (gridContext.recordCount < gridContext.pageSize) {
                selectElement.value = gridContext.recordCount;
            } else {
                selectElement.value = gridContext.pageSize;
            }

        }
    };
};
/*---- talent.ui.Grid end   ----*/

talent.ui.Element = talent.Class.extend({
    element : null,
    /**
     * config:{container:c,properties:{width:"80px",className:"pp"},styles:{padding:""}}
     */
    init : function(_config) {
        this.config = _config ? _config : {};
    },
    setConfig : function(_config) {
        this.config = _config ? _config : {};
    },
    setProperties : function() {
        talent.Util.copy(this.element, this.config.properties);
        talent.Util.setStyle(this.element, this.config.styles);
    },
    render : function() {
        if (!this.element || this.element.hasRendered) {
            this.element = this.create();
        }
        this.config.container.appendChild(this.element);
        this.element.hasRendered = true;
        return this.element;
    }
});

talent.ui.Text = talent.ui.Element.extend({
    /**
     * config:{container:c,properties:{width:"80px",className:"pp",name:"",id:""},styles:{padding:""}}
     */
    init : function(_config) {
        this._super(_config);
    },
    create : function() {
        this.element = tt_ce("input");
        this.element.type = "text";
        // talent.Util.setupDate(this.element, this.config.type);
        this.setProperties();
        return this.element;
    }
});

talent.ui.Date = talent.ui.Text.extend({
    /**
     * config:{container:c,type:"ts,t,d",properties:{width:"80px",className:"pp",name:"",id:""},styles:{padding:""}}
     */
    init : function(_config) {
        this._super(_config);
    },
    create : function() {
        this.element = this._super();
        talent.Util.setupDate(this.element, this.config.type);
        return this.element;
    }
});

talent.ui.Checkbox = talent.ui.Element.extend({
    /**
     * config:{container:c,properties:{width:"80px",className:"pp"},styles:{padding:""}}
     */
    init : function(_config) {
        this._super(_config);
    },
    create : function() {
        element = tt_ce("input");
        element.type = "checkbox";
        this.setProperties();
        return element;
    }
});

talent.ui.Select = talent.ui.Element.extend({
    /**
     * config:{ container:c, items:[ {value:"1",lable/text:"1"},
	 * {value:"2",lable/text:"2"} ], url:"", method:getData,
	 * properties:{width:"80px",className:"pp"}, styles:{padding:""} }
     */
    init : function(_config) {
        this._super(_config);
    },
    create : function() {
        element = tt_ce("select");
        this.setProperties();
        return element;
    }
});

var tt_pager = function(conf) {

    this.renderData = function() {

    };

    this.renderPager = function() {

    };
};
